package com.cong.lock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cong
 * <p>
 * created on 2021/3/31 上午11:32
 */

class ShareData{
   AtomicInteger state = new AtomicInteger();
   ReentrantLock lock = new ReentrantLock();
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();

    public void increment(){
        lock.lock();
        try {
            //多线程判断使用while循环，防止虚假唤醒
            while (state.intValue() !=0){
                c1.await();
            }
            state.getAndIncrement();
            c2.signal();
            System.out.println(state);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void decrement(){

        lock.lock();
        try {
            while (state.intValue()==0){
                c2.await();
            }
            state.decrementAndGet();
            c1.signal();
            System.out.println(state);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}

public class ProdConsumerDemo {
    public static void main(String[] args) {
        ShareData data = new ShareData();
        for (int i = 0; i < 5; i++) {
            new Thread(data::increment,String.valueOf(5)).start();

        }
        for (int i = 0; i < 5; i++) {
            new Thread(data::increment,String.valueOf(5)).start();

        }

        for (int i = 0; i < 5; i++) {
            new Thread(data::decrement,String.valueOf(5)).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(data::decrement,String.valueOf(5)).start();
        }


    }

}
